﻿using System;
using System.IO;
using System.Net;
using System.Text;
using System.Windows.Forms;
using DevelopersToolbox;

namespace NetworkTools {
    public partial class WebRequestControl : UserControl, IExecutableTool {
        public WebRequestControl() {
            InitializeComponent();
        }

        private void _go_Click(object sender, EventArgs e) {
            Execute();
        }

        public void Execute() {
            try {
                Cursor = Cursors.WaitCursor;
                _responseHeaders.Rows.Clear();
                _responseBody.Text = "";

                HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(_url.Text);
                request.Method = _requestMethod.Text;
                foreach (DataGridViewRow row in _requestHeaders.Rows) {
                    string name = (string)row.Cells[0].Value;
                    string value = (string)row.Cells[1].Value;
                    if (name != null && value != null) {
                        request.Headers.Add(name, value);
                    }
                }
                if (request.Method != "GET") {
                    using (Stream requestStream = request.GetRequestStream()) {
                        string body = _requestBody.Text;
                        byte[] buffer = Encoding.ASCII.GetBytes(body);
                        requestStream.Write(buffer, 0, buffer.Length);
                    }
                }

                HttpWebResponse response;
                try {
                    response = (HttpWebResponse)request.GetResponse();
                } catch (WebException webException) {
                    response = (HttpWebResponse)webException.Response;
                }

                _responseStatus.Text = ((int)response.StatusCode) + " - " + response.StatusDescription;

                for (int i = 0; i < response.Headers.Count; i++) {
                    string name = response.Headers.GetKey(i);
                    string value = response.Headers[i];
                    DataGridViewRow dataGridViewRow = new DataGridViewRow();
                    DataGridViewTextBoxCell cell = new DataGridViewTextBoxCell { Value = name };
                    dataGridViewRow.Cells.Add(cell);
                    cell = new DataGridViewTextBoxCell { Value = value };
                    dataGridViewRow.Cells.Add(cell);
                    _responseHeaders.Rows.Add(dataGridViewRow);
                }
                using (Stream responseStream = response.GetResponseStream()) {
                    StreamReader reader = new StreamReader(responseStream);
                    _responseBody.Text = reader.ReadToEnd();
                }
            } finally {
                Cursor = Cursors.Default;
            }
        }
    }
}
